//
//  KLBaseViewController.m
//  Koala
//
//  Created by cao pan on 11/22/14.
//  Copyright (c) 2014 Anonymous. All rights reserved.
//

#import "KLBaseViewController.h"
#import "EXLoadingView.h"

NSString *const kKeyboardWillChangeFrameNotification3    = @"UIKeyboardWillChangeFrameNotification";


@interface KLBaseViewController ()
{
    float  _verticalOffset;
    BOOL   _isKeyboardShow;

    EXLoadingView *_loadingView;

}
@end

@implementation KLBaseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:YES];

    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillChangeFrame:)
                                                 name:kKeyboardWillChangeFrameNotification3 object:nil];

    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkRequestStart)
                                                 name:NNKEY_NETWORK_REQUEST_START
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkRequestFinish)
                                                 name:NNKEY_NETWORK_REQUEST_FINISH
                                               object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kKeyboardWillChangeFrameNotification3
                                                  object:nil];
    [_loadingView dismiss];
}



#pragma mark * Keyboard notifications callback

- (void)setKeybordSlideMode:(KeyboardSlideMode)keybordSlideMode
{
    [[self findFirstResponder:nil] resignFirstResponder];
    self.bKeybordSlideMode = keybordSlideMode;
}

- (void)onKeyboardWillShow:(NSNotification *)note
{
    [self slideUpView:[note userInfo]];
}

- (void)onKeyboardWillHide:(NSNotification *)note
{
    [self slideDownView];
}


- (void)onKeyboardWillChangeFrame:(NSNotification *)note
{
    [self slideShiftView:[note userInfo]];
}

- (void)slideUpView:(NSDictionary *)userInfo
{
    if (_isKeyboardShow)
        return;
    _isKeyboardShow = YES;
    
    if (self.bKeybordSlideMode == KeyboardSlideMode_FitToFirstResponder) {
        CGRect keyboardFrame;
        [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
        float keyboardStartY = CGRectGetMinY(keyboardFrame);
        UIView* field = [self findFirstResponder:[self.view window]];
        CGRect fieldFrame = [[self.view window] convertRect:field.bounds fromView:field];
        float fieldEndY = CGRectGetMaxY(fieldFrame);
        float verticalOffset = MAX(fieldEndY - keyboardStartY, 0);
        
        if (verticalOffset > 0) {
            _verticalOffset = verticalOffset + 1;
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.3];
            
            CGRect frame = self.view.frame;
            frame.origin.y -= _verticalOffset;
            self.view.frame = frame;
            
            [UIView commitAnimations];
        }
    }
    else if (self.bKeybordSlideMode == KeyboardSlideMode_ResizeFrame) {
        [self slideShiftView:userInfo];
    }
}




- (void)slideDownView
{
    if (!_isKeyboardShow)
        return;
    _isKeyboardShow = NO;
    
    if (self.bKeybordSlideMode == KeyboardSlideMode_FitToFirstResponder) {
        if (_verticalOffset > 0) {
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.3];
            
            CGRect frame = self.view.frame;
            frame.origin.y += _verticalOffset;
            self.view.frame = frame;
            
            [UIView commitAnimations];
            
            _verticalOffset = 0;
        }
    }
    else if (self.bKeybordSlideMode == KeyboardSlideMode_ResizeFrame) {
        if (_verticalOffset > 0) {
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.3];
            
            CGRect frame = self.view.frame;
            frame.size.height += _verticalOffset;
            self.view.frame = frame;
            
            [UIView commitAnimations];
            
            _verticalOffset = 0;
        }
    }
}

- (void) slideShiftView:(NSDictionary *)userInfo {
    if (!_isKeyboardShow)
        return;
    if (self.bKeybordSlideMode == KeyboardSlideMode_FitToFirstResponder) {
        CGRect keyboardFrame;
        [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
        float keyboardStartY = CGRectGetMinY(keyboardFrame);
        
        UIView* field = [self findFirstResponder:[self.view window]];
        CGRect fieldFrame = [[self.view window] convertRect:field.bounds fromView:field];
        float fieldEndY = CGRectGetMaxY(fieldFrame);
        
        float verticalOffset = fieldEndY - keyboardStartY;
        
        if (_verticalOffset + verticalOffset > 0) {
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.3];
            
            CGRect frame = self.view.frame;
            frame.origin.y -= verticalOffset;
            self.view.frame = frame;
            _verticalOffset += verticalOffset;
            [UIView commitAnimations];
        }
    }
    else if (self.bKeybordSlideMode == KeyboardSlideMode_ResizeFrame) {
        CGRect keyboardFrame;
        [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
        float verticalOffset = CGRectGetHeight(keyboardFrame);
        
        int adjustedOffset = verticalOffset - _verticalOffset;
        if (adjustedOffset == 0)
            return;
        CGRect frame = self.view.frame;
        _verticalOffset = verticalOffset;
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        
        frame.size.height -=  adjustedOffset;
        self.view.frame = frame;
        [UIView commitAnimations];
    }
}


#pragma mark - Touches events.

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    [[self findFirstResponder:self.view]  resignFirstResponder];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}


- (UIView *)findFirstResponder:(UIView *)baseView {
    if (baseView == nil)
        baseView = self.view;
    
    if (baseView.isFirstResponder)
        return baseView;
    for (UIView *subview in baseView.subviews) {
        UIView *firstResponder = [self findFirstResponder:subview];
        if (firstResponder != nil)
            return firstResponder;
    }
    return nil;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    _loadingView = [[EXLoadingView alloc] init];
    [_loadingView setMessage:@"Loading..."];
    [self.navigationController.view addSubview:_loadingView];
    [self.navigationController.view bringSubviewToFront:_loadingView];
    
    if (self.navigationController.view == nil) {
        [self.view addSubview:_loadingView];
        [self.view bringSubviewToFront:_loadingView];
    }
}


- (void)setLeftButton:(NSString*)title
          normalImage:(NSString*)normalImage
       highlightImage:(NSString*)highLightImage
{
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    
    if(title!=nil){
        [leftButton setTitle:title forState:UIControlStateNormal];
    }
    
    if(normalImage!=nil){
        [leftButton setImage:[UIImage imageNamed:normalImage] forState:UIControlStateNormal];
    }
    
    if(highLightImage!=nil){
        [leftButton setImage:[UIImage imageNamed:highLightImage] forState:UIControlStateHighlighted];
    }
    
    [leftButton addTarget:self action:@selector(leftNavButtonClicked) forControlEvents:UIControlEventTouchUpInside];
//    [leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, -22, 0, 22)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
}


- (void)setRightButton:(NSString*)title
           normalImage:(NSString*)normalImage
        highlightImage:(NSString*)highLightImage
{
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70, 44)];
    [[rightButton titleLabel] setFont:[UIFont systemFontOfSize:13.0f]];
    if(title!=nil){
        [rightButton setTitle:title forState:UIControlStateNormal];
    }
    
    if(normalImage!=nil){
        [rightButton setBackgroundImage:[UIImage imageNamed:normalImage] forState:UIControlStateNormal];
    }
    
    if(highLightImage!=nil){
        [rightButton setBackgroundImage:[UIImage imageNamed:highLightImage] forState:UIControlStateHighlighted];
    }
    
    [rightButton addTarget:self action:@selector(rightNavButtonClicked) forControlEvents:UIControlEventTouchUpInside];
//    [rightButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -22)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}


- (void)leftNavButtonClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)rightNavButtonClicked
{

}


- (void)networkRequestStart
{
    [_loadingView show];
}

- (void)networkRequestFinish
{
    [_loadingView dismiss];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}



@end
